package net.pulseproject.commons.misc;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.grapher.GrapherModule;
import com.google.inject.grapher.InjectorGrapher;
import com.google.inject.grapher.graphviz.GraphvizModule;
import com.google.inject.grapher.graphviz.GraphvizRenderer;

public class GuiceGrapherImpl implements GuiceGrapher {
	
	private static final String OUT_FILE_ENCODING = "UTF-8";
	
	@Override public final void writeGraph(final PrintWriter outWriter, final AbstractModule... guiceModules) {
		final Injector graphInjector = Guice.createInjector(new GrapherModule(), new GraphvizModule());
	    final GraphvizRenderer renderer = graphInjector.getInstance(GraphvizRenderer.class);
	    renderer.setOut(outWriter).setRankdir("TB");
	    
	    final Injector modulesInjector = Guice.createInjector(guiceModules);
	    final InjectorGrapher grapher = graphInjector.getInstance(InjectorGrapher.class);
	    grapher.of(modulesInjector);
	    try {
			grapher.graph();
		} catch (final IOException e) {
			throw new RuntimeException("Creating graph failed!", e);
		}
	}

	@Override public final void writerGraphToFIle(final File outFile, final AbstractModule... guiceModules) {
		final PrintWriter outWriter;
		try {
			outWriter = new PrintWriter(outFile, OUT_FILE_ENCODING);
		} catch (final FileNotFoundException e) {
			throw new RuntimeException("Could not create writer for file [" + outFile.getAbsolutePath() + "]", e);
		} catch (final UnsupportedEncodingException e) {
			throw new RuntimeException("Could not create filer with encoding [" + OUT_FILE_ENCODING + "] " +
					"for file [" + outFile.getAbsolutePath() + "]!", e);
		}
		
		this.writeGraph(outWriter, guiceModules);
	}

	
}
